#!/bin/bash

# 企业职业技能等级认定培训评价工作辅助平台部署脚本
# 作者: Augment Agent
# 版本: 1.0.0

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 命令不存在，请先安装"
        exit 1
    fi
}

# 检查环境
check_environment() {
    log_info "检查部署环境..."
    
    # 检查必要的命令
    check_command "docker"
    check_command "docker-compose"
    check_command "git"
    
    # 检查Docker是否运行
    if ! docker info &> /dev/null; then
        log_error "Docker 服务未运行，请启动 Docker"
        exit 1
    fi
    
    log_success "环境检查通过"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    mkdir -p nginx/ssl
    mkdir -p data/mysql
    mkdir -p data/redis
    mkdir -p data/rabbitmq
    mkdir -p logs/nginx
    mkdir -p logs/app
    mkdir -p files/upload
    
    log_success "目录创建完成"
}

# 生成SSL证书（自签名）
generate_ssl_cert() {
    log_info "生成SSL证书..."
    
    if [ ! -f "nginx/ssl/server.crt" ]; then
        openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
            -keyout nginx/ssl/server.key \
            -out nginx/ssl/server.crt \
            -subj "/C=CN/ST=Beijing/L=Beijing/O=Company/OU=IT/CN=localhost"
        
        log_success "SSL证书生成完成"
    else
        log_info "SSL证书已存在，跳过生成"
    fi
}

# 构建镜像
build_images() {
    log_info "构建Docker镜像..."
    
    # 构建后端镜像
    log_info "构建后端镜像..."
    docker build -f Dockerfile.server -t eval-server:latest .
    
    # 构建前端镜像
    log_info "构建前端镜像..."
    docker build -t eval-web:latest ./yudao-ui/yudao-ui-admin-vue3/yudao-ui-admin-vue3-master/
    
    log_success "镜像构建完成"
}

# 启动服务
start_services() {
    log_info "启动服务..."
    
    # 停止现有服务
    docker-compose -f docker-compose.eval.yml down
    
    # 启动新服务
    docker-compose -f docker-compose.eval.yml up -d
    
    log_success "服务启动完成"
}

# 等待服务就绪
wait_for_services() {
    log_info "等待服务就绪..."
    
    # 等待MySQL就绪
    log_info "等待MySQL服务..."
    while ! docker-compose -f docker-compose.eval.yml exec mysql mysqladmin ping -h"localhost" --silent; do
        sleep 2
    done
    
    # 等待Redis就绪
    log_info "等待Redis服务..."
    while ! docker-compose -f docker-compose.eval.yml exec redis redis-cli ping; do
        sleep 2
    done
    
    # 等待后端服务就绪
    log_info "等待后端服务..."
    while ! curl -f http://localhost:48080/admin-api/infra/health &> /dev/null; do
        sleep 5
    done
    
    log_success "所有服务已就绪"
}

# 初始化数据库
init_database() {
    log_info "初始化数据库..."
    
    # 等待MySQL完全启动
    sleep 10
    
    # 执行数据库初始化脚本
    docker-compose -f docker-compose.eval.yml exec mysql mysql -uroot -p123456 ruoyi-vue-pro < /docker-entrypoint-initdb.d/基于芋道系统的数据库结构设计.sql
    docker-compose -f docker-compose.eval.yml exec mysql mysql -uroot -p123456 ruoyi-vue-pro < /docker-entrypoint-initdb.d/eval_dict_data.sql
    docker-compose -f docker-compose.eval.yml exec mysql mysql -uroot -p123456 ruoyi-vue-pro < /docker-entrypoint-initdb.d/eval_menu_data.sql
    docker-compose -f docker-compose.eval.yml exec mysql mysql -uroot -p123456 ruoyi-vue-pro < /docker-entrypoint-initdb.d/eval_init_data.sql
    
    log_success "数据库初始化完成"
}

# 显示部署信息
show_deployment_info() {
    log_success "部署完成！"
    echo ""
    echo "=========================================="
    echo "  企业职业技能等级认定培训评价工作辅助平台"
    echo "=========================================="
    echo ""
    echo "访问地址："
    echo "  前端地址: https://localhost"
    echo "  后端API:  https://localhost/admin-api"
    echo "  接口文档: http://localhost:48080/doc.html"
    echo ""
    echo "管理员账号："
    echo "  用户名: admin"
    echo "  密码: admin123"
    echo ""
    echo "数据库信息："
    echo "  地址: localhost:3306"
    echo "  数据库: ruoyi-vue-pro"
    echo "  用户名: root"
    echo "  密码: 123456"
    echo ""
    echo "Redis信息："
    echo "  地址: localhost:6379"
    echo "  密码: 123456"
    echo ""
    echo "RabbitMQ信息："
    echo "  管理界面: http://localhost:15672"
    echo "  用户名: admin"
    echo "  密码: admin123"
    echo ""
    echo "常用命令："
    echo "  查看日志: docker-compose -f docker-compose.eval.yml logs -f [服务名]"
    echo "  重启服务: docker-compose -f docker-compose.eval.yml restart [服务名]"
    echo "  停止服务: docker-compose -f docker-compose.eval.yml down"
    echo "=========================================="
}

# 主函数
main() {
    log_info "开始部署企业职业技能等级认定培训评价工作辅助平台..."
    
    check_environment
    create_directories
    generate_ssl_cert
    build_images
    start_services
    wait_for_services
    show_deployment_info
    
    log_success "部署完成！"
}

# 处理命令行参数
case "${1:-deploy}" in
    "deploy")
        main
        ;;
    "start")
        log_info "启动服务..."
        docker-compose -f docker-compose.eval.yml up -d
        log_success "服务启动完成"
        ;;
    "stop")
        log_info "停止服务..."
        docker-compose -f docker-compose.eval.yml down
        log_success "服务停止完成"
        ;;
    "restart")
        log_info "重启服务..."
        docker-compose -f docker-compose.eval.yml restart
        log_success "服务重启完成"
        ;;
    "logs")
        docker-compose -f docker-compose.eval.yml logs -f ${2:-}
        ;;
    "status")
        docker-compose -f docker-compose.eval.yml ps
        ;;
    "clean")
        log_warning "清理所有数据和镜像..."
        read -p "确认清理所有数据？(y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            docker-compose -f docker-compose.eval.yml down -v --rmi all
            docker system prune -f
            log_success "清理完成"
        else
            log_info "取消清理"
        fi
        ;;
    "help"|"-h"|"--help")
        echo "企业职业技能等级认定培训评价工作辅助平台部署脚本"
        echo ""
        echo "用法: $0 [命令]"
        echo ""
        echo "命令:"
        echo "  deploy   部署系统（默认）"
        echo "  start    启动服务"
        echo "  stop     停止服务"
        echo "  restart  重启服务"
        echo "  logs     查看日志"
        echo "  status   查看状态"
        echo "  clean    清理数据"
        echo "  help     显示帮助"
        ;;
    *)
        log_error "未知命令: $1"
        echo "使用 '$0 help' 查看帮助"
        exit 1
        ;;
esac
